<template>
  <div class="app-container" id="app-main">
    <!-- 查询和其他操作 -->
    <div>
      <div class="filter-container">
        <el-input
          v-model="keyword"
          clearable
          size="small"
          class="filter-item-left"
          style="width: 200px"
          :placeholder="$t('message.jurisdiction.placeholder')"
          @keyup.enter="handleFind"
        />
        <el-button class="filter-item-right" icon="el-icon-search" size="small" @click="handleFind">
          {{ $t('message.operate.search') }}
        </el-button>

        <el-button
          class="filter-item"
          type="primary"
          icon="el-icon-refresh"
          size="small"
          @click="handleReset"
        >
          {{ $t('message.operate.reset') }}
        </el-button>
      </div>
      <div class="filter-container filter-container2">
        <el-button
          v-limit="'XTGL:QXGL:ADD'"
          class="filter-item"
          type="primary"
          size="small"
          icon="el-icon-plus"
          @click="handleAdd"
        >
          {{ $t('message.operate.add') }}
        </el-button>
      </div>
    </div>

    <el-table
      v-loading="loading"
      :max-height="maxHeight"
      :data="tableData"
      border
      height="550"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center"></el-table-column>
      <!-- <el-table-column :label="$t('message.jurisdiction.index')" width="50" align="center">
        <template #default="scope">
          <span>{{ scope.$index + 1 }}</span>
        </template>
      </el-table-column> -->
      <el-table-column type="index" :index="indexMethod" align="center" label="序号" width="50" fixed="left" />
      <el-table-column :label="$t('message.jurisdiction.powerName')" align="center">
        <template #default="scope">
          <span>{{ scope.row.powerName }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('message.jurisdiction.powerCompleteness')" align="center">
        <template #default="scope">
          <span>{{ scope.row.powerCompleteness }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('message.jurisdiction.powerDescribe')" align="center">
        <template #default="scope">
          <span>{{ scope.row.powerDescribe }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('message.jurisdiction.createUsername')" align="center">
        <template #default="scope">
          <span>{{ scope.row.createUsername }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('message.jurisdiction.createTime')" align="center">
        <template #default="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('message.jurisdiction.modifyUsername')" align="center">
        <template #default="scope">
          <span>{{ scope.row.modifyUsername }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('message.jurisdiction.modifyTime')" align="center">
        <template #default="scope">
          <span>{{ scope.row.modifyTime }}</span>
        </template>
      </el-table-column>
      <el-table-column
        :label="$t('message.operate.operate')"
        fixed="right"
        width="200"
        align="center"
      >
        <template #default="scope">
          <!--<el-button @click="handRest(scope.row)" type="warning" size="small">重置密码</el-button>-->
          <el-button
            v-limit="'XTGL:QXGL:EDIT'"
            size="small"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
          >
            {{ $t('message.operate.edit') }}
          </el-button>
          <el-button
            v-limit="'XTGL:QXGL:DELETE'"
            size="small"
            icon="el-icon-delete"
            type="danger"
            @click="handleDelete(scope.row)"
          >
            {{ $t('message.operate.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页-->
    <div class="pagination">
      <el-pagination
        v-model="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next, jumper"
        :total="total"
        background
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加或修改对话框 -->
    <el-dialog v-model="dialogFormVisible" :title="title" :width="dialogWidth" append-to-body>
      <el-form ref="form" :model="form" :rules="dataRule">
        <el-form-item
          :label="$t('message.jurisdiction.powerName')"
          :label-width="formLabelWidth"
          prop="powerName"
        >
          <el-input
            v-model="form.powerName"
            auto-complete="off"
            :placeholder="$t('message.validate.input')"
          />
        </el-form-item>

        <el-form-item
          :label="$t('message.jurisdiction.powerDescribe')"
          :label-width="formLabelWidth"
          prop="powerDescribe"
        >
          <el-input
            v-model="form.powerDescribe"
            auto-complete="off"
            :placeholder="$t('message.validate.input')"
          />
        </el-form-item>

        <el-form-item :label="$t('message.jurisdiction.powerMenu')" :label-width="formLabelWidth">
          <el-tree
            ref="menuTree"
            v-loading="menuLoading"
            :data="menuData"
            size="mini"
            show-checkbox
            check-strictly
            node-key="menuId"
            :props="defaultProps"
            element-loading-text="拼命加载中"
            @check-change="handleMenuCheckChange"
          >
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <span>{{ node.label }}</span>
                <span v-if="Object.keys(data.children).length != 0" style="margin: 0 40px 0 0">
                  <el-checkbox v-model="data.selectAll" @change="ChangeAppend(data)"
                    >选中全部子级</el-checkbox
                  >
                </span>
              </span>
            </template>
          </el-tree>

          <div style="padding-left: 24px; padding-top: 12px">
            <el-checkbox v-model="checkAll" :disabled="false" @change="handleCheckAll">
              <b>{{ $t('message.operate.all') }}</b>
            </el-checkbox>
          </div>
        </el-form-item>
      </el-form>
      <template #footer class="dialog-footer">
        <el-button size="small" @click="dialogFormVisible = false">
          {{ $t('message.operate.cancel') }}
        </el-button>
        <el-button size="small" type="primary" @click="submitForm">
          {{ $t('message.operate.confirm') }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  addPower,
  updatePower,
  deletePower,
  findPowerMenus,
  getJurisdictionrList,
} from '../api/jurisdiction.ts'
import initDict from '../utils/initDict.js'
import { get } from 'lodash'
// import { mapGetters } from 'vuex'
import { getMenus } from '../api/menu'
import { servicesLoading } from '@/utils/loading'

export default {
  components: {
    // NewImport,
  },
  mixins: [initDict],
  emits: ['close'],
  data() {
    return {
      // 用户列表
      tableData: [],
      // roles: [], // 角色列表
      // jobs: [], // 岗位列表
      // operation: false, // true:新增, false:编辑
      currentPage: 1,
      pageSize: 10,
      total: 0, // 总数量
      // deptId: '',
      dialogFormVisible: false, // 控制弹出框
      formLabelWidth: '120px',
      keyword: '',

      // deptData: [],
      deptTreeProps: {
        label: 'name',
        children: 'children',
      },
      // value5: '100',
      // filterText: '',
      loading: false,
      // jobName: '',
      multipleSelection: [],
      form: {
        powerName: '',
        powerDescribe: '',
        powerMenuList: [],
      },
      // 分类菜单列表
      menuData: [],
      // tree配置项
      defaultProps: {
        children: 'children',
        label: 'name',
      },
      // 表单校验
      dataRule: {
        powerName: [
          { required: true, message: this.$i18n.t('message.validate.required'), trigger: 'blur' },
        ],
        powerDescribe: [
          { required: true, message: this.$i18n.t('message.validate.required'), trigger: 'blur' },
        ],
        fetchMenu: [
          { required: true, message: this.$i18n.t('message.validate.required'), trigger: 'blur' },
        ],
      },
      title: '',
      isEditForm: false,
      selectRole: {},
      checkAll: false,
      height: 0,
    }
  },
  computed: {
    maxHeight() {
      return this.height - 158
    },
    // ...mapGetters(['maxHeightTable', 'ismobile']),
    rules() {
      return {}
    },
  },
  created() {
    this.findTreeData()
    this.JurisdictionList()
    this.setDialogWidth()
  },
  mounted() {
    this.height = document.getElementById('app-main').offsetHeight
  },
  methods: {
    setDialogWidth() {
      this.dialogWidth = '50%'
      // if (this.ismobile) {
      //   this.dialogWidth = '90%'
      // } else {
      //   this.dialogWidth = '50%'
      // }
    },
    indexMethod (index){
      return this.pageSize*(this.currentPage-1) +index+1
    },
    handleSelectionChange(val) {
      console.log(val)
    },
    // 加载用户列表
    JurisdictionList() {
      this.loading = true
      const params = new URLSearchParams()
      params.append('current', this.currentPage)
      params.append('size', this.pageSize)
      // params.append('deptId', this.deptId)
      // params.append('username', this.query.userName)
      getJurisdictionrList(params, { keyword: this.keyword }).then((response) => {
        this.loading = false
        this.tableData = get(response, 'data.data.records', [])
        this.total = get(response, 'data.data.total', 0)
      })
    },
    // // 获取角色
    // roleList: function() {
    //   this.loading = true
    //   const params = {
    //     keyword: this.query.roleName,
    //     roleType: '1',
    //   }
    //   getRoles(params).then(response => {
    //     this.tableData = response.data.data
    //     this.loading = false
    //   })
    // },
    // 获取菜单树
    async findTreeData() {
      try {
        this.menuLoading = true
        const res = await getMenus()
        this.menuData = get(res, 'data.data', [])
        this.menuLoading = false
      } catch (err) {
        console.log(err)
      }
    },
    ChangeAppend(item) {
      if (item.selectAll) {
        // 选中当前级
        const parentId = item.menuId
        this.$refs.menuTree.setChecked(parentId, true, false)
        // 选中子级
        item.children.forEach((element) => {
          this.$refs.menuTree.setChecked(element.menuId, true, false)
          if (Object.keys(element.children).length != 0) {
            this.fnPitchOn(element.children, item.selectAll)
          }
        })
      } else {
        item.children.forEach((element) => {
          this.$refs.menuTree.setChecked(element.menuId, false, false)
          if (Object.keys(element.children).length != 0) {
            this.fnPitchOn(element.children, item.selectAll)
          }
        })
      }
    },
    fnPitchOn(item, key) {
      for (let i in item) {
        if (Object.keys(item[i].children).length != 0) {
          if (item[i].children.length == 1) {
            if (key) {
              const parentId = item[i].menuId
              this.$refs.menuTree.setChecked(parentId, true, false)
            } else {
              const parentId = item[i].menuId
              this.$refs.menuTree.setChecked(parentId, false, false)
            }
          }
          this.fnPitchOn(item[i].children, key)
        } else {
          if (key) {
            const parentId = item[i].parentId
            this.$refs.menuTree.setChecked(parentId, true, false)
            this.$refs.menuTree.setChecked(item[i].menuId, true, false)
          } else {
            const parentId = item[i].parentId
            this.$refs.menuTree.setChecked(parentId, false, false)
            this.$refs.menuTree.setChecked(item[i].menuId, false, false)
          }
        }
      }
    },
    // 树节点选择监听
    // handleMenuCheckChange(data, check) {
    //   if (check) {
    //     //  节点选中时同步选中父节点
    //     // const parentId = data.parentId
    //     // this.$refs.menuTree.setChecked(parentId, true, false)
    //   } else {

    //     // 节点取消选中时同步取消选中子节点
    //     if (Object.keys(data.children).length != 0) {
    //       data.children.forEach(element => {
    //         this.$refs.menuTree.setChecked(element.id, false, false)
    //       })
    //     }
    //   }
    // },
    // 全选操作
    handleCheckAll() {
      if (this.checkAll) {
        const allMenus = []
        this.checkAllMenu(this.menuData, allMenus)
        this.$refs.menuTree.setCheckedNodes(allMenus)
      } else {
        this.$refs.menuTree.setCheckedNodes([])
      }
    },
    // 递归全选
    checkAllMenu(menuData, allMenus) {
      menuData.forEach((menu) => {
        allMenus.push(menu)
        if (menu.children) {
          this.checkAllMenu(menu.children, allMenus)
        }
      })
    },

    handleFind: function () {
      this.JurisdictionList()
    },
    handleReset: function () {
      this.keyword = ''
      this.JurisdictionList()
    },
    // 添加权限
    handleAdd() {
      this.dialogFormVisible = true
      this.title = this.$i18n.t('message.jurisdiction.addJurisdiction')
      this.form = {
        powerName: '',
        powerDescribe: '',
        powerMenuList: [],
      }
      //点击新增时，清除选中菜单
      if (this.$refs.menuTree != undefined) {
        this.$refs.menuTree.setCheckedNodes([])
      }
      this.isEditForm = false
    },

    // 编辑权限
    handleEdit: async function (row) {
      this.isEditForm = true
      this.title = this.$i18n.t('message.jurisdiction.editJurisdiction')
      this.form = JSON.parse(JSON.stringify(row))
      await this.handleRoleSelectChange(row.id)
      // this.dialogFormVisible = true
    },

    // 角色选择改变监听
    handleRoleSelectChange(id) {
      this.selectRole.id = id
      const loading = servicesLoading({ fullscreen: true })
      findPowerMenus(id)
        .then((res) => {
          this.dialogFormVisible = true
          loading.close()
          console.log(res.data.data,'findPowerMenus');
          this.$nextTick(()=>{
            this.$refs.menuTree.setCheckedNodes(res.data.data)
          })
          // setTimeout(() => {
          // }, 10);
        })
        .catch((err) => {
          loading.close()
          console.error(err)
        })
    },

    handleDelete: function (row) {
      const that = this
      this.$confirm(this.$i18n.t('message.hint.isDelete'), this.$i18n.t('message.operate.hint'), {
        confirmButtonText: this.$i18n.t('message.operate.confirm'),
        cancelButtonText: this.$i18n.t('message.operate.cancel'),
        type: 'warning',
      }).then(() => {
        deletePower([{ id: row.id }]).then((response) => {
          if (response.data.code === 200) {
            this.$message({
              type: 'success',
              message: response.data.msg,
            })
            that.JurisdictionList()
          } else {
            this.$message({
              type: 'error',
              message: response.data.msg,
            })
          }
        })
      })
    },
    submitForm: function () {
      // if (this.form.dsType === 4 && this.deptIds.length === 0) {
      //   this.$message({
      //     message: this.$i18n.t('message.role.warning'),
      //     type: 'warning',
      //   })
      //   return
      // } else {
      // const depts = []
      // if (this.form.dsType === 4) {
      //   for (let i = 0; i < this.deptIds.length; i++) {
      //     depts.push(this.deptIds[i])
      //   }
      //   this.form.roleDepts = depts
      // }
      // }
      const powerId = this.selectRole.id !== '' ? this.selectRole.id : '0'
      const checkedNodes = this.$refs.menuTree.getCheckedNodes(false, true)
      const roleMenus = []
      for (let i = 0, len = checkedNodes.length; i < len; i++) {
        const roleMenu = { powerId: powerId, menuId: checkedNodes[i].menuId }
        roleMenus.push(roleMenu)
      }
      // 得到选中树的角色id和菜单id
      this.form.powerMenuList = roleMenus
      // 得到机构ids
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const loading = servicesLoading({ fullscreen: true })
          if (this.isEditForm) {
            updatePower(this.form).then((response) => {
              loading.close()
              if (response.data.code === 200) {
                this.$message({
                  type: 'success',
                  message: response.data.msg,
                })
                this.dialogFormVisible = false
                this.JurisdictionList()
              } else {
                this.$message({
                  type: 'error',
                  message: response.data.msg,
                })
              }
            })
          } else {
            addPower(this.form).then((response) => {
              loading.close()
              if (response.data.code === 200) {
                this.$message({
                  type: 'success',
                  message: response.data.msg,
                })
                this.dialogFormVisible = false
                this.JurisdictionList()
              } else {
                this.$message({
                  type: 'error',
                  message: response.data.msg,
                })
              }
            })
          }
        }
      })
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.JurisdictionList()
    },
    // 加载机构列表
    // findDeptTree: function() {
    //   getDeptTree().then(res => {
    //     this.deptData = res.data.data
    //   })
    // },
    // changeScope() {
    //   this.deptIds = []
    //   if (this.form.dsType === 4) {
    //     this.findDeptTree()
    //   }
    // },
  },
}
</script>
<style scoped lang="scss">
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
